import { message } from '../../functionalComponent';
import { execServiceAdapter, hasServiceAdapter, iup } from '../../util';
import { columnsToTableColumns, queryItemsToFormItems } from './utils';
// reference_source_table_type  来源引用
// generate_target_table_human_type 生成目的单
const bizTypeArray = ['reference_source_table_type', 'generate_target_table_human_type'];
// 后端不判断空值，只能前端来处理了
function omitNull(data) {
  if (!data || !iup.isObject(data)) {
    return data;
  }
  return Object.keys(data).reduce((p, k) => {
    if (!iup.isNullOrEmpty(data[k], '')) {
      p[k] = data[k];
    }
    return p;
  }, {});
}

/**
 * 根据业务类型获取可用的业务流列表
 */
export async function getFlowList({ bizCode, orgId, tenantId, bizType, contractTypes }) {
  const [success, result] = await iup.request.bodyWithArray({
    url: '/iup-rule-engine/flow/definition/getFlowDefinitionChoseList',
    data: omitNull({ bizCode, orgId, tenantId, bizType: bizTypeArray[bizType], contractTypes })
  });
  if (success) {
    return result;
  }
  iup.alert(result);
  return void 0;
}

/**
 * 获取来源树
 */
export async function loadSourceTree({ bizCode, tableName, flowCode, sourceBizCode }) {
  const [success, result] = await iup.request.getWithArray({
    url: '/iup-rule-engine/helpInfo/getTreeHelpInfo',
    data: omitNull({ targetBizCode: bizCode, targetTable: tableName, flowCode, sourceBizCode })
  });
  if (success) {
    const sourceNodes: any[] = [];
    iup.loopChildren({ children: result }, (node) => {
      if (node.mappingFormId) {
        sourceNodes.push(node);
      } else {
        node.disabled = true;
      }
    });
    return [result, sourceNodes];
  }
  return [result, []];
}

/**
 * 获取来源的配置信息
 * @param sourceId 来源id
 */
export async function loadSourceConfig({ sourceId }) {
  const [success, result] = await iup.request.getWithArray({
    url: '/iup-rule-engine/helpInfo/getHelpInfoById',
    data: omitNull({ id: sourceId })
  });
  !success && iup.alert(result);
  if (success) {
    const {
      ruleHelpInfoList = [],
      ruleHelpInfoQueryList = [],
      masterRuleHelpInfoList = [],
      masterRuleHelpInfoQueryList = [],
      popupName,
      targetTableType,
      allowMultiSelect,
      popupMode,
      masterFormId,
      treeFieldConfig,
      treeField
    } = result;
    return {
      ...result,
      popupMode,
      popupName,
      allowMultiSelect: targetTableType === 0 ? 0 : allowMultiSelect ?? 0,
      columns: columnsToTableColumns(ruleHelpInfoList),
      queryItems: queryItemsToFormItems(ruleHelpInfoQueryList),
      // 主表要用的
      masterColumns: columnsToTableColumns(masterRuleHelpInfoList),
      masterQueryItems: queryItemsToFormItems(masterRuleHelpInfoQueryList),
      masterFormId,
      treeFieldConfig,
      treeField
    };
  }
  return { columns: [], queryItems: [], popupName: '' };
}

/**
 * 获取来源的数据信息
 */
export async function loadSourceData({
  sourceId,
  pageIndex,
  pageSize,
  queryCondition,
  flowCode,
  busData,
  popupMode,
  masterId,
  treeFilterValue
}: any) {
  // getRef('table').current.getApi().setExtraParam({ queryCondition });
  const urlSuffix = popupMode == 1 ? 'getTreeHelpInfoList' : 'getHelpInfoList';
  if (!sourceId) {
    return {};
  }
  const [success, result] = await iup.request.bodyWithArray({
    // getTreeHelpInfoList
    url: '/iup-rule-engine/helpInfo/' + urlSuffix,
    data: omitNull({
      id: sourceId,
      pageIndex,
      pageSize,
      queryCondition: queryCondition || {},
      flowCode,
      configMap: busData || {},
      masterId,
      treeFilterValue
    })
  });
  !success && iup.alert(result);
  return success ? result : { total: 0, list: [] };
}

/**
 * 转换来源数据
 */
export async function converSourceData({ sourceId, flowCode, sourceDatas, detailTables, mainRuleHelpInfo }) {
  const data = {
    id: sourceId,
    flowCode,
    sourceDatas,
    mainRuleHelpInfo: mainRuleHelpInfo?.sourceDatas?.length ? mainRuleHelpInfo : null
  };
  const [success, result] = await iup.request.bodyWithArray({
    url: '/iup-rule-engine/helpInfo/mappingAimDatas',
    data: omitNull(detailTables ? { ...data, detailTables } : data)
  });
  !success && iup.alert(result);
  if (success && iup.isArray(result)) {
    return [
      success,
      result.reduce((p, d) => {
        const tmp = { ...p, [d.tableName]: d.data };
        if (d.modelName) {
          tmp[d.modelName] = d.data;
        }
        return tmp;
      }, {})
    ];
  }
  return [success, result];
}

/**
 * 获取通用帮助树数据
 * @param param
 * @returns
 */
export async function getTreeList({ helpId, clientSqlFilter }) {
  const params: any = {
    node: 'root'
  };
  if (clientSqlFilter) {
    if (iup.isObject(clientSqlFilter)) {
      params.clientJsonFilter = clientSqlFilter;
    } else {
      params.clientSqlFilter = iup.CryptoJS.encode(clientSqlFilter);
    }
  }
  if (iup.isFunction(helpId)) {
    helpId = await helpId();
  }
  if (hasServiceAdapter('commonHelp', 'getTreeList')) {
    return await execServiceAdapter('commonHelp', 'getTreeList', { ...params, helpId });
  }
  const {
    code,
    data,
    message: msg
  } = await iup.request.body({
    url: `baseservice/comhelp/getComHelpTreeList`,
    data: {
      ...params,
      helpId
    }
  });
  if (code === 0) {
    return data;
  }
  msg && message.error(msg);
  return [];
}

/**
 * 来源帮助-已选择
 */
export async function getSeletcedList(params) {
  const [success, result] = await iup.request.bodyWithArray({
    url: '/iup-rule-engine/helpInfo/getSelectedList',
    data: omitNull(params)
  });
  !success && iup.alert(result);
  return success ? result : { total: 0, list: [] };
}

/**
 * 检测是否生成待办任务
 * @params
 * @flowCode string
 * @returns  { "generateTask": true, "needUser": true }// 是否需要生成代办任务，需要user用户帮助
}}
 */
export async function checkGenerateTask(params: {
  flowCode: string;
  bizCode: string;
  instanceId?: string;
  bizId?: string;
}): Promise<{ generateTask: boolean; needUser: boolean }> {
  const { code, data } = await iup.request.get({
    url: '/iup-rule-engine/flow/definition/checkGenerateTask',
    data: omitNull(params)
  });
  code !== 0 && iup.alert(data);
  return code === 0 ? data : { generateTask: false, needUser: false };
}

/**
 * 生成代办任务
 */
export async function autoGenerateTask(params: {
  flowCode: string;
  bizCode: string;
  bizId: string;
  userNos?: string[];
}) {
  const [success, result] = await iup.request.bodyWithArray({
    url: '/iup-rule-engine/flow/definition/generateTask',
    data: omitNull(params)
  });
  !success && iup.alert(result);
  return success;
}
